import urllib2
import smtplib  
from email.mime.text import MIMEText
import sys
import time
from bs4 import BeautifulSoup
reload(sys)
sys.setdefaultencoding('utf-8')

base_url = 'http://www.zhihu.com'
_mail_user = ''
_mail_pwd = ''
_mail_suffix = 'qq.com'
_mail_signature = ''
_mail_list = []

def get_daily_hot (html):
	global current_index
	soup = BeautifulSoup (html.encode ('utf8'), 'html.parser')
	soup_temp = soup.find ('div', {'data-type' : 'daily'}, recursive = 'false')
	if (soup_temp):
		soup = soup_temp
	for daily in soup.find_all ('div', {'class':'explore-feed feed-item'}, recursive = 'false'):
		if (daily):
			header = daily.find ('a', {'class' : 'question_link'}, recursive = 'false')
			idx = daily.get ('data-offset')
			url = base_url + header.get ('href')
			#print url
			report =  '<a href=\'' + url + '\'>' + idx + '. ' + header.string + '<\\a><br>\n'
			"""
			print 'Top ', idx
			print header.string
			print 'Url : ', base_url + header.get ('href')
			"""
			return idx, report
	return 0, ""

def send_mail(to_list, sub, content):
	me = _mail_signature + '<' + _mail_user + '@' + _mail_suffix + '>'
	msg = MIMEText (content , _subtype = 'html' , _charset = 'utf-8')
	msg['Subject'] = sub
	msg['From'] = me
	msg['To'] = ";".join (to_list)
	try:
		s = smtplib.SMTP ()
		s.connect ('smtp.' + _mail_suffix)
		s.login (_mail_user, _mail_pwd)
		s.sendmail (me, to_list, msg.as_string ())
		s.close ()
		return True
	except Exception, e:
		print str (e)
		return False

if __name__ == "__main__":
	ISOTIMEFORMAT = '%y-%m-%d ZhiHu daily hot'
	sub = time.strftime (ISOTIMEFORMAT, time.localtime())
	request = urllib2.Request ('http://www.zhihu.com/explore')
	idx, res = get_daily_hot (urllib2.urlopen (request).read ())
	while (idx != 0):
		#http://www.zhihu.com/node/ExploreAnswerListV2?params=%7B%22offset%22%3A5%2C%22type%22%3A%22day%22%7D
		#json format is {'offset' : 5, 'type' : 'day'}
		request = urllib2.Request ('http://www.zhihu.com/node/ExploreAnswerListV2?params=%7B%22offset%22%3A' + str (idx) + '%2C%22type%22%3A%22day%22%7D')
		idx , tmp = get_daily_hot (urllib2.urlopen (request).read ().encode ('utf-8'))
		res += tmp
	print res
	send_mail (_mail_list, sub, res)
